package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import cn.edu.swu.miniwebsvr.handler.EchoHandler;
import cn.edu.swu.miniwebsvr.handler.TimeHandler;
import java.util.HashMap;
import java.util.Map;


public class Config {
    private final int port = 8080;
    private final String webRoot = "webroot";
    private final Map<String, Handler> handlerMap = new HashMap<>();

    private Config() {
        handlerMap.put("/", new DefaultHandler());
        handlerMap.put("/time", new TimeHandler());
        handlerMap.put("/echo", new EchoHandler());
    }

    public static Config getInstance() {
        return Holder.INSTANCE;
    }

    private static class Holder {
        private static final Config INSTANCE = new Config();
    }

    public int getPort() {
        return port;
    }

    public String getWebRoot() {
        return webRoot;
    }

    public Handler getHandler(String url) {
        // TODO: [222024321072055/苏雨征] 实现 URL 精确匹配或基础路径匹配逻辑
        //优先精确匹配
        Handler exactHandler = handlerMap.get(url);
        if (exactHandler != null) {
            return exactHandler;
        }

        //精确匹配失败则尝试匹配基础路径（从URL中逐步截取父路径进行匹配）
        String currentPath = url;
        while (true) {
            // 截取父路径（例如 "/a/b/c" -> "/a/b"，"/a/b" -> "/a"，"/a" -> "/"）
            int lastSlashIndex = currentPath.lastIndexOf('/');
            if (lastSlashIndex <= 0) { // 到达根路径 "/" 时停止
                break;
            }
            currentPath = currentPath.substring(0, lastSlashIndex);
            Handler parentHandler = handlerMap.get(currentPath);
            if (parentHandler != null) {
                return parentHandler;
            }
        }

        //所有路径均无匹配则返回默认处理器
        return handlerMap.get("/");
    }
}
